package cn.texous.easytalk.manager.db;

import com.zaxxer.hikari.HikariDataSource;
import org.h2.tools.RunScript;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.io.File;
import java.io.FileReader;
import java.sql.Connection;

/**
 * insert description here.
 *
 * @author Showa.L
 * @since 2019/10/23 17:41
 */
@Component
public class BaseDbUnit {

    protected static DataSource DATASOURCE;
    @Autowired
    private DataSource dataSource;

    @PostConstruct
    public void setUp() {
        HikariDataSource ds = (HikariDataSource) dataSource;
        System.out.println(ds.getJdbcUrl());
        // validate jdbc url, Prevent resignation voluntarily due to sql statement execution environment error
        if (ds.getJdbcUrl() != null && ds.getJdbcUrl().startsWith("jdbc:h2:mem:db_test;MODE=MYSQL")) {
            DATASOURCE = dataSource;
//            initializeDatabase("/h2_db/build/schema.sql");
        }
    }

    /**
     * Runs script that insert relevant test data into the Mock DB table
     * according to the child class that calls it
     */
    public static void initializeDatabase(String... sqlFiles) {
        try {
            if (sqlFiles != null) {
                for (String sqlFile : sqlFiles) {
                    File script = new File(BaseDbUnit.class.getResource("/" + sqlFile).getFile());
                    Connection connection = DATASOURCE.getConnection();
                    RunScript.execute(connection, new FileReader(script));
                    connection.close();
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("could not initialize with script");
        }
    }

}
